package com.zoffy.ybuhelper;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.iflytek.sparkchain.core.*;
import com.zoffy.ybuhelper.adapter.GPTRecycleAdapter;
import com.zoffy.ybuhelper.dao.MessageDao;
import com.zoffy.ybuhelper.database.YBUDatabase;
import com.zoffy.ybuhelper.pojo.entity.Message;

import java.util.ArrayList;
import java.util.List;

public class FireGPTActivity extends AppCompatActivity {

    private LLM llm;
    private List<Message> dataList = new ArrayList<>();;
    private GPTRecycleAdapter adapter;
    private Boolean isFinish=true;
    private int size=0,totalSize=-1;
    private MessageDao messageDao;

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firegpt);
        init();

    }
    private void getMessage(){
        if (totalSize==-1){
            totalSize=messageDao.countMessage();
        }
        List<Message> messageList=new ArrayList<>();
        if(totalSize>size){
            messageList=messageDao.getMessage(size,Integer.min(4,totalSize-size));
            size+=messageList.size();
            for (int i = 0; i <messageList.size() ; i++) {
                adapter.addLeft(messageList.get(i));
            }
            adapter.notifyItemRangeInserted(0,messageList.size());
        }
    }
    private void sendMessage(String message){
        if(llm==null){
            gptInit();
        }
        llm.arun(message);
    }
    private void init(){
        YBUDatabase gptDatabase=MyApplication.getInstance().getYBUDatabase();
        messageDao = gptDatabase.messageDao();
        recycleInit();
        buttonInit();
        refreshInit();
    }
    protected void refreshInit(){
        SwipeRefreshLayout refreshLayout=findViewById(R.id.refresh_layout);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getMessage();
                        refreshLayout.setRefreshing(false);

                    }
                },500);

            }
        });
    }
    protected void buttonInit(){
        EditText inputEdit=findViewById(R.id.input_message);
        Button sendButton=findViewById(R.id.send_button);
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isFinish){
                    String message=inputEdit.getText().toString();
                    if(!"".equals(message)){
                        isFinish=false;

                        Message newMessage=new Message();
                        newMessage.setOrigin(0);
                        newMessage.setMessage(message);
                        adapter.add(newMessage);
                        adapter.notifyItemInserted(adapter.size()-1);

                        sendMessage(message);
                        messageDao.insert(newMessage);
                        isFinish=true;
                    }
                    else {
                        Toast.makeText(FireGPTActivity.this,"消息不能为空",Toast.LENGTH_SHORT).show();
                    }
                    inputEdit.setText("");
                }
                else{
                    Toast.makeText(FireGPTActivity.this,"请等待上一个问题结束后再发送",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    private void recycleInit(){
        RecyclerView recyclerView=findViewById(R.id.recycle_message);
        adapter = new GPTRecycleAdapter(dataList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this,RecyclerView.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }
    private void gptInit(){
        String appID,apiKey,apiSecret;
        SharedPreferences sharedPreferences=getSharedPreferences("user_data",MODE_PRIVATE);
        appID=sharedPreferences.getString("appId","");
        apiKey=sharedPreferences.getString("apiKey","");
        apiSecret=sharedPreferences.getString("apiSecret","");
        //从平台获取的授权appid，apikey,apisecrety
        SparkChainConfig config =  SparkChainConfig.builder()
                .appID(appID)
                .apiKey(apiKey)
                .apiSecret(apiSecret);
        int ret = SparkChain.getInst().init(getApplicationContext(), config);
        Log.d("调试信息","sdk init:"+ret);

        LLMConfig llmConfig = LLMConfig.builder();
        llmConfig.domain("generalv2");
        llmConfig.url("ws(s)://spark-api.xf-yun.com/v2.1/chat");//如果使用generalv2，domain和url都可缺省，SDK默认；如果使用general，url可缺省，SDK会自动补充；如果是其他，则需要设置domain和url。
        llm = new LLM(llmConfig);

        LLMCallbacks llmCallbacks = new LLMCallbacks() {
            @Override
            public void onLLMResult(LLMResult llmResult, Object usrContext) {
                switch (llmResult.getStatus()){
                    //数据状态 start
                    case 0:
                        isFinish=false;
                        Message newMessage=new Message();
                        newMessage.setOrigin(1);
                        newMessage.setMessage(llmResult.getContent());
                        adapter.add(newMessage);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter.notifyItemInserted(adapter.size()-1);
                            }
                        });
                        break;
                    //数据状态 continue
                    case 1:
                        Message preMessage=adapter.get(adapter.size()-1);
                        preMessage.setMessage(preMessage.getMessage()+llmResult.getContent());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter.notifyItemChanged(adapter.size()-1);
                            }
                        });
                        break;
                    //数据状态 end
                    case 2:

                        Message endMessage= adapter.get(adapter.size()-1);
                        endMessage.setMessage(endMessage.getMessage()+llmResult.getContent());
                        messageDao.insert(endMessage);
                        isFinish=true;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter.notifyItemChanged(adapter.size()-1);
                            }
                        });
                        break;
                    default:
                        break;
                }

                Log.d("调试信息","异步调用：" +  "onLLMResult:" + " " + llmResult.getRole() + " " + llmResult.getContent());
            }

            @Override
            public void onLLMEvent(LLMEvent event, Object usrContext) {
                Log.w("调试信息","onLLMEvent:" + " " + event.getEventID() + " " + event.getEventMsg());
            }

            @Override
            public void onLLMError(LLMError error, Object usrContext) {
                isFinish=true;
                Message newMessage=new Message();
                newMessage.setOrigin(1);
                newMessage.setMessage(error.getSid());
                adapter.add(newMessage);
                runOnUiThread(new Runnable() {
                    @Override
                        public void run() {
                            adapter.notifyItemInserted(adapter.size()-1);
                    }
                });
                Log.e("调试信息","onLLMError:" + " " + error.getErrCode() + " " + error.getErrMsg());
            }
        };
        llm.registerLLMCallbacks(llmCallbacks);
    }

}
